﻿#include <zemb/Socket.h>
#include <zemb/Tracer.h>
#include <zemb/FileUtil.h>
#include <zemb/StrUtil.h>
#include <zemb/ArgUtil.h>

using namespace zemb;

class MyUdpServer : public UdpServer{
public:
    bool onNewDatagram(UdpSocket& udpSocket,char* buf, int len)
    {
    	udpSocket.sendData((const char *) buf, len, 1000);
		return true;
    }   
};

int main(int argc, char* argv[])
{
	ArgOption  option;
	uint16 port=5555;
	std::string ip = "0.0.0.0";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	Tracer::getInstance().addSink(std::make_shared<STDSink>()).start();

	if (!option.parseArgs(argc,argv))	/* 解析参数 */
	{
		return RC_ERROR;
	}
	if(option.hasOption("h")>=0)
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("udp server help:");
		TRACE_YELLOW("%s [-h] [-p port] [-i ip]",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help");
		TRACE_YELLOW("        -p  server port");
		TRACE_YELLOW("        -i  server ip");
		return RC_OK;
	}

	if(option.hasOption("p")>0)
	{
		port = (uint16)std::stoi(option.getValue("p")[0]);
	}
	else
	{
		TRACE_ERR("udp server need a port: [-p port]!");
		return RC_ERROR;
	}
	
	if(option.hasOption("i")>0)
	{
		ip = option.getValue("i")[0];
	}

	Thread serThread;
    MyUdpServer server;
    if (!server.setup(ip,port))
    {
    	TRACE_ERR("udp server init error: %s:%d",CSTR(ip),port);
		return RC_ERROR;
	}
    if (!serThread.start(server))
    {
    	TRACE_ERR("udp server start error.");
		return RC_ERROR;
	}
	Thread::msleep(2000);
	TRACE_INFO("udp server start ok: %s:%d",CSTR(ip),port);
	while(1)
	{
		Thread::msleep(2000);
	}
    return 0;
}
